<?php

// +----------------------------------------------------------------------
// |ZBPHP[基于ThinkPHP5.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2019 http://www.benbenwangluo.com
// +----------------------------------------------------------------------
// | Author 似水星辰 [ 2630481389@qq.com ]
// +----------------------------------------------------------------------
// | 中犇软件 技术六部 出品
// +----------------------------------------------------------------------
namespace app\customer\model;

use think\Model;

/**
 * 会话
 * @author 晓风<215628355@qq.com>
 * @date 2021-5-26 9:19:54
 */
class Session extends Model {

    // 设置当前模型对应的完整数据表名称
    protected $table = '__CUSTOMER_SESSION__';
    // 自动写入时间戳
    protected $autoWriteTimestamp = true;
    //设置主键
    protected $pk = "aid";

     /**
     * 获取文档列表
     * @param mixed $map 筛选条件
     * @param mixed $order 排序
     * @return mixed
     * @author 晓风<215628355@qq.com>
     */
    public static function getList($map = [], $order = []) {
        return self::where($map)
                ->order($order)
                ->paginate();
    }
      /**
     * 获取会话列表-普通用户端
     * @param int $user_id 会员ID
     * @return mixed
     * @author 晓风<215628355@qq.com>
     */
    public static function getSessionList($user_id) {
        return self::view("customer_session")
                ->view("customer_shop","store_name as nickname,store_logo as head_img","customer_session.store_id = customer_shop.store_id")    
                ->where("customer_session.user_id",$user_id)    
                ->where("customer_session.user_delete",0)
                ->order("customer_session.update_time desc")
                ->paginate();
    }
       /**
     * 获取会话列表-客服服务端
     * @param int $user_id 会员ID
     * @return mixed
     * @author 晓风<215628355@qq.com>
     */
    public static function getServerSessionList($user_id , $stores ,$pageSize = 20) {
        return self::view("customer_session")
                ->view("customer_shop","store_name,store_logo","customer_session.store_id = customer_shop.store_id")    
                ->view("user","user_nickname as nickname, head_img","customer_session.user_id = user.id") 
                ->where("customer_session.store_id","in",$stores)    
                ->where("customer_session.service_user_id",$user_id)   
                ->where("customer_session.service_delete",0)
                ->order("customer_session.update_time desc")
                ->paginate($pageSize);
    }
    /**
     * 获取客户的未读
     * @param int $user_id 会员ID
     * @return mixed
     * @author 晓风<215628355@qq.com>
     */
    public static function getNoread($user_id) {
        return self::where("user_id",$user_id)->sum("user_noread");
    }

    /**
     * 获取客户的第一条未读
     * @return float
     * @author php迷途小书童
     * @created 2021/1/23 17:40
     */
    public static function getFirstNoread($user_id) {
        return self::where("user_id",$user_id)->order('aid', 'desc')->find();
    }
    /**
     * 检测有无写入会话
     * @author 晓风<215628355@qq.com>
     * @param int $store_id 店铺ID
     * @param int $user_id 客户会员ID
     * @return type
     */
    public static function checkSession(int $store_id ,int $user_id){
        return self::where("store_id",$store_id)->where("user_id",$user_id)->find();
    }
    /**
     * 添加聊天会话
     * @author 晓风<215628355@qq.com>
     * @param Store   $store      店铺信息
     * @param int     $user_id    发件人会员ID (客服ID或客户ID)
     * @param int     $to_user_id 客户会员ID (客户ID)
     * @param string  $content    内容
     * @param int     $form_type  发件人类型 1用户 2客服    
     * @return self
     * @throws \Exception
     */    
    public static function addInfo(Shop $store,int $user_id , int $to_user_id, string $content ,int $form_type = 1){   
         //若已聊过，则拉取会话中的信息
        $session = self::checkSession($store["store_id"],$to_user_id);
        $service_user_id =  empty($session['service_user_id']) ? 0 : $session['service_user_id'] ;     
        //获取全部连线客服
        $services = Customer::getLineServices($store["store_id"]);//Customer::where("store_id",$store["store_id"])->column("status","member_id");
                
        //若是客服主动拉起会话，判断TA的权限
        if($form_type == 2){
            if(!isset($services[$user_id])){
                throw new \Exception("你还不是该店铺的客服",5000);  
            }   
            //若之前的会话并没有客服服务，则分配到这个客服
            if(empty($session["service_user_id"])){ //包括没有会话的情况
                 $service_user_id = $user_id;
            }
            //若之前的会话有客服服务，则判断会话是否已超时            
            if($session && $session["update_time"] < time() - 7200){
                $service_user_id =  $user_id;
            }
            if(!$service_user_id){
                throw new \Exception("已分配给其他客服，请耐心等待",5001); 
            }               
        }
        //若是用户发起的会话，不判断TA的权限，若未分配客服,或者客服未连线，则随机分配一个
        else if(!$service_user_id || empty($services[$service_user_id])){
          
            $service_user_id = Customer::getServiceDataToRandId($services);           
        }   
        //没有找到客服，则存储到离线消息里
        if(!$service_user_id){
            $service_user_id = 0;          
        }
        if( $service_user_id > 0){
            Chat::where("store_id",$store["store_id"])->where("user_id",$to_user_id)->where("service_user_id",0)->setField("service_user_id",$service_user_id);
        }
        $time = time();
        $noread = $form_type == 2 ? "user_noread" : "service_noread";
        $data = [    
            "user_delete"=>0,
            "service_delete"=>0,
            "service_user_id"=>$service_user_id,
            "content"=>$content,               
            "update_time"=>$time,           
        ];
        
        if($session ){
            $data["count"] = ['inc',1];  
            $data[$noread] = ['inc',1];             
            $res = self::where("aid",$session["aid"])->update($data);
        }else{
            $data["count"] =1;  
            $data[$noread] = 1;
            $data["store_id"] = $store["store_id"];
            $data["user_id"] = $to_user_id; 
            $res = self::create($data);
        }    
        if(!$res){
            throw new \Exception("生成会话失败",5003);
        }    
        return [
            "form_type"=>$form_type,
            "store_id"=>$store["store_id"],
            "user_id"=>$to_user_id,
            "service_user_id"=>$service_user_id,
        ];
    } 
    /**
     * 删除会话/客服下线
     * @author 晓风<215628355@qq.com>
     * @param int $user_id 客服ID
     * @param int $store_id
     * @param int $formType 1-用户角度 2-客服角度
     * @return type
     */
    public static function delSession(int $user_id ,int $store_id , int $formType = 1){
        $formField = $formType == 1 ? "user_id" : "service_user_id";
        $field = $formType == 1 ? "user_delete" : "service_delete";       
        $up[$field]=1;
        if($formType == 2){
            $up["service_user_id"]=0;
        }
        self::where($formField,$user_id)->where("store_id",$store_id)->update($up);   
        return true;        
    }
     /**
     * 清空未读
     * @author 晓风<215628355@qq.com>
     * @param int $user_id
     * @param int $store_id
     * @param int $formType 1-用户角度 2-客服角度
     * @return type
     */
    public static function clearSessionNoRead(int $user_id ,int $store_id  , int $formType = 1){
        $formField = $formType == 1 ? "user_id" : "service_user_id";
        $field = $formType == 1 ? "user_noread" : "service_noread";   
        return self::where($formField,$user_id)->where("store_id",$store_id)->setField($field,0);
    }    
 
    /**
     * 批量清空未读
     * @author 晓风<215628355@qq.com>
     * @param int $user_id
     * @param array $store_id
     * @param int $formType 1-用户角度 2-客服角度
     * @return type
     */
    public static function clearSessionNoReadIds(int $user_id ,array $store_id = [] , int $formType = 1){
        $formField = $formType == 1 ? "user_id" : "service_user_id";
        $field = $formType == 1 ? "user_noread" : "service_noread";           
        if(!$store_id){
            return self::where($formField,$user_id)->setField($field,0);
        }            
        return self::where($formField,$user_id)->where("store_id","in",$store_id)->setField($field,0);
    }
    
     /**
     * 聊天中的时间展示
     * @param $time
     * @author 晓风<215628355@qq.com>
     * @return bool|false|string
     */
     public static function chatDate($time)
    {        
        $toDay =  date('Y-m-d');
        $date = date("Y-m-d",$time);
        //判断是不是今天
        if($date == $toDay){
            return date("H:i",$time);
        }
         //判断是不是昨天
        if($date == date('Y-m-d', strtotime("-1 day"))){
           return "昨天";
        }
        //判断是不是今年
        if(date("Y",$time) == date('Y')){
           return  date("m-d",$time);
        }  
        return $date;
    }
    
}
